package portal.monitor.cmd;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

import portal.monitor.utils.MonBaseUtils;
import portal.monitor.utils.MonConfig;
import utils.Log4jInit;

//public class ExcuCmd implements Callable<String> {
public class ExcuCmd {
	
private String methodName;
private Map<String,Object> paramsMap;

	
	public String getMethodName() {
	return methodName;
}

public void setMethodName(String methodName) {
	this.methodName = methodName;
}

public Map<String, Object> getParamsMap() {
	return paramsMap;
}

public void setParamsMap(Map<String, Object> paramsMap) {
	this.paramsMap = paramsMap;
}

public ExcuCmd(){}

public ExcuCmd(String method,Map<String,Object> paramsMap){
	this.methodName = method;
	this.paramsMap = paramsMap;
}

	public static String download_deploy(String localFileName,String ip,boolean deploy){
		
		//C:\nse\bin\jhexecproxy\etc\fileclient.exe  -m 192.168.1.211 -l C:/nse/license.dat -r /apps/monitor/deploy/license.dat -d -p 6522 -n jhadmin
		String command = MonConfig.remoteExecPath+MonConfig.fileclient + " -m " + MonConfig.localhost + " -l " + MonConfig.remoteBase +localFileName + " -r " +MonConfig.localBase+"deploy/"+localFileName
				+ " -d -p 6522 -n jhadmin";
		
		String upload = ExcuCmd.execclient3(command,ip);	
		if(upload.contains("success")&& deploy){
			String unzipCmd = MonConfig.winrar+" x "+ MonConfig.remoteBase +localFileName +" "+MonConfig.remoteBase;  //unzip
			upload = ExcuCmd.execclient3(unzipCmd,ip);
			String temp = localFileName.substring(0,localFileName.lastIndexOf("."));
			Log4jInit.logger.info("temp::"+temp);
			String deployCmd = MonConfig.remoteBase +localFileName+temp;
		  upload = ExcuCmd.execclient3(deployCmd,ip);
		}
		
		return upload;
	}
	
	public static String exec(String cmd){
		
		try{
			Process process = null;
			//System.out.println(shellString);
			process = Runtime.getRuntime().exec(cmd);			
//			return processExe(process ,resultKey);			
		} catch (IOException e){
			e.printStackTrace();
			return "ERROR";
		} 
		
		return "SUCCESS";
	}
	
	
	
	public static String command2(String command) {
        try {
            //String command = "ping "+ip;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            ByteArrayInputStream inputStream =new ByteArrayInputStream("y".getBytes());
            CommandLine commandline = CommandLine.parse(command);
            DefaultExecutor exec = new DefaultExecutor();
            ExecuteWatchdog watchdog = new ExecuteWatchdog(20*1000);//等待60秒，超时推出
            exec.setExitValue(1);
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream,inputStream);
            exec.setWatchdog(watchdog);
            ///System.out.println("commandline:"+commandline);
            exec.setStreamHandler(streamHandler);
            DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
            //streamHandler
            //watchdog.
            exec.execute(commandline,resultHandler);
            inputMessage(outputStream,watchdog);
            //outputStream.write("y\r".getBytes());
            
            resultHandler.waitFor(60000);
            //inputStream.
            //exec.getStreamHandler().
            String out = outputStream.toString("gbk");
            String error = errorStream.toString("gbk");
            return out+error;
        } catch (Exception e) {
            Log4jInit.logger.error("ping task failed.",e);
            return e.getMessage();
        }
    }
	
	private static void inputMessage(final OutputStream output,final ExecuteWatchdog wa){
		new Thread(new Runnable() {
		      public void run() {
		        OutputStreamWriter writer = new OutputStreamWriter(output);
		        BufferedWriter bw = new BufferedWriter(writer);
		        //String line = null;
		        try{
			        	while(wa.isWatching()){
			            bw.write("y");
			            bw.newLine();
			            TimeUnit.SECONDS.sleep(3);;
			            }
		        } catch (IOException e) {
		            e.printStackTrace();
		         	} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        }
		    }).start();
	}
	
	
	public static String execclient3(String cmd,String ip){
		
		String execPath = ExcuCmd.class.getResource("/"+MonConfig.execclientUri).getPath();
		Log4jInit.logger.info("execPath::"+execPath);
		try {
			MonBaseUtils.chmod(execPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		/root/git/ClusterCtrl/SIC304/target/classes/execclient -m 192.168.1.3 -c  "C:/jhexecproxy/etc/fileclient.exe -m 192.168.1.211 -l C:\nse\deploy\GIS.exe -r /apps/monitor/deploy/GIS.exe -d -p 6522 -n jhadmin"
		
		String command = execPath + " -m "+ip+" -c  \""+cmd+"\"" ;
		String scriptPath = CommCmd.makeExcScript(command);
		Log4jInit.logger.info("==========scriptPath:"+scriptPath);
		String retStr = CommCmd.getCmdRetStr(scriptPath);
		Log4jInit.logger.info("retStr::"+retStr);
		return retStr;
	}
	
	public static void main(String[] args){
		
		//String cmd = ExcuCmd.download_deploy("GIS.exe 1","192.168.1.3",false);
		String cmd = ExcuCmd.download_deploy("SP.exe","192.168.1.3",false);
		Log4jInit.logger.info("RETURN : "+cmd);
		
	}

	/*@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		String method = this.methodName;
		String result = "";
		if(method.equals("download_deploy")){
			result =	ExcuCmd.download_deploy(this.paramsMap.get(0).toString(), this.paramsMap.get(1).toString(), (Boolean)this.paramsMap.get(2));
		}else if(method.equals("execclient3")){
			result = ExcuCmd.execclient3(this.paramsMap.get(0).toString(), this.paramsMap.get(1).toString());
		}
		
		return result;
	}*/
	
	
}
